package com.template.service.impl;

import com.template.dto.Meal;
import com.template.mapper.MealMapper;
import com.template.service.PageService;
import com.template.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PageServiceImpl implements PageService {
    @Autowired
    private MealMapper mealMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void pageCount(Long userId, String pageName) {
        Long mealId= mealMapper.selectMealId(userId);
        Meal meal=mealMapper.selectMeal(mealId);

        Class<?> clazz = meal.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if (field.getName().equals(pageName)) {
                    Object value = field.get(meal);
                    int intValue = (Integer) value;//将object类型转为int类型
                    intValue++;
//                    System.out.println("给"+meal+"加"+intValue);
                    field.set(meal, intValue);
                    mealMapper.UpdateMealCount(meal);
                }
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public Meal getPageCount(Long userId) {

        System.out.println("当前登录的id"+ UserContext.getCurrentUserId());
//        通过userId获取到相对应的pageId
        Long mealId= mealMapper.selectMealId(userId);

//        通过pageId获取到相对应的meal信息
        Meal meal=mealMapper.selectMeal(mealId);

        return meal;
    }

    @Override
    public void addPojo(String name) {

        String mealPath = "template-pojo/src/main/java/com/template/dto/Meal.java"; // 文件路径
//        String mealPath = "src/main/java/org/example/imageuploadspringboot/demos/pojo/Meal.java"; // 文件路径
        String insertStr = "private Integer "+name+";";

        //往实体类pojo\meal中添加对象
        try (BufferedReader reader = new BufferedReader(new FileReader(mealPath))) {
            List<String> lines = new ArrayList<>();
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            // 在倒数第二行后添加新行
            if (lines.size() > 1) {
                lines.add(lines.size() - 1, insertStr);
            } else {
                // 如果文件只有一行，则直接在该行后面添加
                lines.add(insertStr);
            }
            // 写回文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(mealPath))) {
                for (String l : lines) {
                    writer.write(l);
                    writer.newLine();
                }
            }
            log.info("往meal类中添加"+name+"对象成功");
        } catch (IOException e) {
            log.info("往meal类中添加"+name+"对象失败");
            e.printStackTrace();
        }


        //往数据库中的meal表添加字段
        String sql = "ALTER TABLE meal ADD COLUMN " + name+" INT DEFAULT 0";
        try {
            jdbcTemplate.execute(sql);
            log.info("成功往meal表中添加字段: " + name);
        } catch (Exception e) {
            System.out.println("往meal表中添加字段失败: " + e.getMessage());
        }


        //往mapper/MealMapper中更新sql语句

        String mealMeaperPath = "template-server/src/main/java/com/template/mapper/MealMapper.java"; // 文件路径
//        String mealMeaperPath = "src/main/java/org/example/imageuploadspringboot/demos/mapper/MealMapper.java"; // 文件路径
        try {
            // 读取文件内容
            StringBuilder contentBuilder1 = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new FileReader(mealMeaperPath))) {
                String currentLine;
                while ((currentLine = br.readLine()) != null) {
                    contentBuilder1.append(currentLine).append("\n");
                }
            }

            // 修改内容
            String fileContent1 = contentBuilder1.toString();
            fileContent1 = fileContent1.replace("@Insert(\"insert into meal(crud,cssStyle,test,richTextEditor,forum) values (#{crud},#{cssStyle},#{test},#{richTextEditor},", "@Insert(\"insert into meal(crud,cssStyle,test,richTextEditor,"+name+",forum) values (#{crud},#{cssStyle},#{test},#{richTextEditor},#{"+name+"},");
            fileContent1 = fileContent1.replace(" @Update(\"update meal set crud=#{crud},cssStyle=#{cssStyle},test=#{test},richTextEditor=#{richTextEditor},", " @Update(\"update meal set crud=#{crud},cssStyle=#{cssStyle},test=#{test},richTextEditor=#{richTextEditor},"+name+"=#{"+name+"},");

            // 写回文件
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(mealMeaperPath))) {
                bw.write(fileContent1);
            }

            log.info("mealmapper文件修改成功！");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("mealmapper文件修改失败！");
        }

        //往mapper/MealMapper中更新sql语句

        String UserServiceImplPath = "template-server/src/main/java/com/template/service/impl/UserServiceImpl.java"; // 文件路径
//        String UserServiceImplPath = "src/main/java/org/example/imageuploadspringboot/demos/service/impl/UserServiceImpl.java"; // 文件路径
        try {
            // 读取文件内容
            StringBuilder contentBuilder2 = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new FileReader(UserServiceImplPath))) {
                String currentLine;
                while ((currentLine = br.readLine()) != null) {
                    contentBuilder2.append(currentLine).append("\n");
                }
            }

            // 修改内容
            String fileContent2 = contentBuilder2.toString();
            fileContent2 = fileContent2.replace("meal.setForum(0);", "meal.setForum(0);\nmeal.set"+ StringUtils.capitalize(name)+"(0);");

            // 写回文件
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(UserServiceImplPath))) {
                bw.write(fileContent2);
            }

            log.info("UserServiceImpl文件修改成功！");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("UserServiceImpl文件修改失败！");
        }
    }



}
